package websimulator;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class CheckLogin
 * Servlet uses in most of pages of WebSimulator and checks if user is eligible
 * by checking username in sessions id
 */
@WebServlet("/CheckLogin")
public class CheckLogin extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private HttpSession httpsession;   
    private String username = null;
    private String password = null;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CheckLogin() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if (request != null){
		processRequest(request, response);
		}
		else{
			response.sendRedirect("Login.jsp");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		httpsession = request.getSession();
		response.setContentType("text/html");
		username = request.getParameter("username");
        password = request.getParameter("password");

        //checks if username and password are not empty and redirects to login form if they are not correct
        if ((password !="")&(username !="")){
        	if (askDatabase()){
            	httpsession.setAttribute("username", username);
                response.sendRedirect("Menu.jsp");
            }
            else{
            	response.sendRedirect("Login.jsp");
            }
        }
        else{
        	response.sendRedirect("Login.jsp");
        }
	}
	
	/**
	 * 
	 * @return true (if user and password are correct) false (if there are not correct)
	 */
	protected boolean askDatabase(){
		Connector con;
		boolean access = false;
		try {
			con = new Connector();
			access = con.LoginStatement(username, password);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		return access;
	}
}
